#!/usr/bin/python env
# -*- coding: utf-8 -*-
# @Time   :2018/4/18 19:28
# @Author :huchao
# __all__ = ["input_student","output_student",'delte_UserInfo','update_UserScore','score_HightoLow','age_HightoLow','student_dict_move','student_IO_Write','get_student_for_file']

docs = list()  # 这个列表用来记录全部的学生信息
from StudentClass import Student

# 此函数用来录入学生信息：
def input_student():
    '''
    input_student()
        #直接调用即可返回一个学生信息列表，学生信息用字典的形式保存
    :return: studentdata #用列表形式返回学生信息列表
    '''
    name = input("请输入学生的姓名")
    if not name:
        return
    age = int(input("请输入学生的年龄"))
    assert 0 <= age <= 140, "您输入的年龄有错误"
    score = int(input("请输入学生的成绩"))
    assert 0 <= score <= 100, "您输入的成绩不合法"
    address = input("请输入学生家庭住址")
    return Student(name, age, score,address)


def inputStudentInfo():
    '''
    用来返回对外开放接受输入学生的信息
    :return:
    '''
    while True:
        try:
            stu = input_student()
            if not stu:
                break
        except AssertionError as err:
            print(err)
        except TypeError as err:
            print(err)


# 此函数用来打印已经录入的学生信息：
def output_student(docs):
    """
    output_studeng(studentData)
        用字符串表格的形式打印学生信息
    :param studentData:
    :return: None
    """
    width = max([len(stu.getStudentName()) for stu in docs]) + 4  # 测试数据
    lienNum = len(Student.getStudentArry())
    # 打印第一行表头
    print(("+" + "-" * (width - 2)) * lienNum + "+")
    print("|" + "Student Info exle".center(width * 3 - 4) + "|")
    exleline = ("+%s" % ("-" * (width - 2))) * lienNum + "+"
    print(exleline)
    print(("|" + "{}|" * lienNum).format(*[x.center(width - 2) for x in Student.getStudentArry()]))
    print(exleline)
    # 打印学生信息
    for stu in docs:
        # 获得学生的信息的列表然后格式化之后打印输出
        print(("|" + "{}|" * lienNum).format(stu.getStudentName().center(width - 2),
                                             str(stu.getStudentage()).center(width - 2),
                                            str(stu.getStudentScore()).center(width - 2),
                                             stu.getStudentAddres().center(width - 2)))
        print(exleline)


def delte_UserInfo():
    """
    按照学生姓名删除学生的信息
    :param docs: 学生信息列表
    :return: None
    """
    docs = Student.getStudentList()
    name = input("请输入要删除的学生姓名：(退出删除输入q)")
    if name == "q":
        return
    assert name in [stu.getStudentName() for stu in docs], "您要删除的学生不存在！"
    for stu in docs:
        if name == stu.getStudentName():
            docs.remove(stu)


def deletStudent():
    '''开放接口，用来删除学生信息'''
    while True:
        try:
            if not delte_UserInfo():
                break
        except AssertionError as err:
            print(err)


def update_UserScore(docs):
    """
    按照学生的名字修改学生的成绩
    :param docs: 学生信息列表
    :return: None
    """
    name = input("请输入要删除的学生姓名：(退出删除输入q)")
    if name == "q":
        return
    assert name in [stu.getStudentName() for stu in docs], "您要删除的学生不存在！"
    score = input("请输入学生修改后的学生成绩：（退出输入q）")
    if score == "q":
        return
    assert 0 <= int(score) <= 100, "您输入的成绩不是一个合法的值！"
    for stu in docs:
        if name == stu.getStudentName:
            stu.setStudentScore(int(score))


def updateStudent():
    '''开放接口用来更新学生信息'''
    docs = Student.getStudentList()
    while True:
        try:
            if not update_UserScore(docs):
                break
        except AssertionError as err:
            print(err)


def score_HightoLow(reverse=False):
    """
    score_HightoLow(docs,reverse =False)
    :param docs:
    :return: 按照成绩从高到底返回学生信息列表
    """
    docs = Student.docs
    return sorted(docs, key=lambda stu: stu.getStudentScore(), reverse=reverse)


def age_HightoLow(reverse=False):
    """
    age_HightoLow(docs,reverse =False)
    :param docs:
    :param reverse:
    :return: 按照年龄从高到低返回学生信息列表
    """
    docs = Student.getStudentList()
    return sorted(docs, key=lambda stu: stu.getStudentage(), reverse=reverse)


def outPutStudentlistOniter(key=None, reverse=False):
    '''
    按照一定规则打印学生信息
    :param key: 排序依据
    :param reverse: 正序还是逆序
    :return:None
    '''
    docs = Student.getStudentList()
    if key == None:
        output_student(docs)
    elif key == "score":
        output_student(score_HightoLow(reverse))
    elif key == "age":
        output_student(age_HightoLow(reverse))

def student_dict_move():
    '''
    把存放学生信息的dict list 以学生为单位返回可迭代对象
    :param dict:
    :return:
    '''
    list = Student.getStudentList()
    for stu in list:
        yield str(stu)

# 把这两个接口的功能封装尽student类中
def student_IO_Write():
    '''
    把处理好的字符串写入文件中
    :param list:
    :return:
    '''
    try:
        with open("si.txt",mode="w") as file:
            for stu in Student.getStudentList():
                stu.writeInfoToFile(file)
            print("学生信息已经存到文件中")
    except IOError:
        print("si.txt文件读取错误")


def get_student_for_file():
    '''
    读取文件中的学生信息，组成字典列表之后返回这个列表
    :return:
    '''
    with open("si.txt",mode="rt") as file:
        Student.readStudentListForFile(file)
    print("学生信息加载完毕")
